#pragma once 

#include<iostream>
#include<pthread.h>
#include<signal.h>
#include"TcpServer.hpp"
#include"log.hpp"
#include"Task.hpp"
#include"ThreadPoll.hpp"

#define PORT 8888

class HttpServer
{
private:
    int port;
    // TcpServer*tcp_server;
    // ThreadPoll thread_poll;
    bool stop; //标记服务状态
public:
    // HttpServer(int _port=PORT)
    // :port(_port),tcp_server(nullptr),stop(false)
    // {}

    HttpServer(int _port=PORT)
    :port(_port),stop(false)
    {}

    void InitServer()
    {
        //避免写入时，server崩溃，忽略SIGPIPE信号
        signal(SIGPIPE,SIG_IGN);
        // tcp_server = TcpServer::getinstance(port);
    }

    //启动服务
    void Loop()
    {
        TcpServer*tsvr = TcpServer::getinstance(port);
        LOG(INFO,"Loop begin")
        // int listen_sock = tcp_server->Sock();
        while(!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // int sock = accept(listen_sock ,(struct sockaddr*)&peer,&len);
            int sock = accept(tsvr->Sock(),(struct sockaddr*)&peer,&len);
            if(sock<0)
            {
                continue;
            }
            LOG(INFO,"Get a new link");

            //构建任务
            Task task(sock);
            //向线程池中传入任务z
            ThreadPoll::getinstance()->PushTask(task);

            //获取新连接后，交付给线程进行处理
        //     int *_sock = new int(sock);
        //     pthread_t tid;
        //     pthread_create(&tid,nullptr,Entrance::HandlerRequest,_sock);
        //     pthread_detach(tid);//线程 分离
        }
    }
    ~HttpServer()
    {}
};